const db = require('../models/database');

// 获取所有脚本来源详情
exports.getAllScriptSources = async (req, res) => {
  try {
    // 获取所有脚本来源
    const sources = await db.all(`
      SELECT 
        s.id, s.name, s.description, s.created_at, s.updated_at
      FROM script_sources s
      ORDER BY s.name
    `);
    
    // 获取每个脚本来源的事件数量
    for (const source of sources) {
      const result = await db.get(`
        SELECT COUNT(*) as event_count
        FROM events
        WHERE script_source = ?
      `, [source.name]);
      
      source.event_count = result ? result.event_count : 0;
    }
    
    res.status(200).json({
      success: true,
      sources: sources.map(source => ({
        ...source,
        created_at_formatted: new Date(source.created_at).toLocaleString('zh-CN'),
        updated_at_formatted: new Date(source.updated_at).toLocaleString('zh-CN')
      }))
    });
  } catch (error) {
    console.error('获取脚本来源详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取脚本来源详情失败',
      error: error.message
    });
  }
};

// 添加新的脚本来源
exports.addScriptSource = async (req, res) => {
  try {
    const { name, description } = req.body;
    
    if (!name) {
      return res.status(400).json({
        success: false,
        message: '脚本来源名称不能为空'
      });
    }
    
    const now = Date.now();
    
    try {
      const result = await db.run(`
        INSERT INTO script_sources (name, description, created_at, updated_at)
        VALUES (?, ?, ?, ?)
      `, [name, description || '', now, now]);
      
      res.status(201).json({
        success: true,
        message: '脚本来源添加成功',
        source_id: result.lastID
      });
    } catch (err) {
      if (err.message.includes('UNIQUE constraint failed')) {
        res.status(409).json({
          success: false,
          message: '脚本来源名称已存在'
        });
      } else {
        throw err;
      }
    }
  } catch (error) {
    console.error('添加脚本来源错误:', error);
    res.status(500).json({
      success: false,
      message: '添加脚本来源失败',
      error: error.message
    });
  }
};

// 更新脚本来源
exports.updateScriptSource = async (req, res) => {
  try {
    const { id } = req.params;
    const { description } = req.body;
    
    if (!id) {
      return res.status(400).json({
        success: false,
        message: '脚本来源ID不能为空'
      });
    }
    
    const now = Date.now();
    
    const result = await db.run(`
      UPDATE script_sources
      SET description = ?, updated_at = ?
      WHERE id = ?
    `, [description || '', now, id]);
    
    if (result.changes === 0) {
      return res.status(404).json({
        success: false,
        message: '脚本来源不存在'
      });
    }
    
    res.status(200).json({
      success: true,
      message: '脚本来源更新成功'
    });
  } catch (error) {
    console.error('更新脚本来源错误:', error);
    res.status(500).json({
      success: false,
      message: '更新脚本来源失败',
      error: error.message
    });
  }
};
